package top.easyblog.core.atomic;

import com.google.common.collect.Iterables;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import top.easyblog.common.request.QueryUrlMappingRequest;
import top.easyblog.core.dao.auto.mapper.UrlMappingMapper;
import top.easyblog.core.dao.auto.model.UrlMapping;
import top.easyblog.core.dao.auto.model.UrlMappingExample;
import top.easyblog.core.util.JsonUtils;

import java.util.Date;

/**
 * @author: frank.huang
 * @date: 2023-12-17 23:26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AtomicUrlMappingService {

    private final UrlMappingMapper urlMappingMapper;


    public void insertOne(UrlMapping urlMapping) {
        urlMapping.setCreateTime(new Date());
        urlMappingMapper.insertSelective(urlMapping);
        log.info("[DB]Insert new url mapping.Detail==>{}", JsonUtils.toJSONString(urlMapping));
    }


    public UrlMapping queryByRequest(QueryUrlMappingRequest request) {
        if (StringUtils.isBlank(request.getCompressCode()) &&
                StringUtils.isBlank(request.getSourceUrlDigest())) {
            log.info("短链映射查询参数都是空");
            return null;
        }

        UrlMappingExample urlMappingExample = new UrlMappingExample();
        UrlMappingExample.Criteria criteria = urlMappingExample.createCriteria();
        if (StringUtils.isNotBlank(request.getSourceUrlDigest())) {
            criteria.andSourceUrlDigestEqualTo(request.getSourceUrlDigest());
        }
        if (StringUtils.isNotBlank(request.getCompressCode())) {
            criteria.andCompressionCodeEqualTo(request.getCompressCode());
        }
        return Iterables.getFirst(urlMappingMapper.selectByExample(urlMappingExample), null);
    }


}
